//
//  TableViewController.m
//  iOSPractice
//
//  Created by hoolai on 2018/11/26.
//  Copyright © 2018年 hoolai. All rights reserved.
//

#import "RoleViewController.h"
#import "MenuViewController.h"

@interface RoleViewController ()<UITableViewDataSource,UITableViewDelegate>
@property (weak, nonatomic) IBOutlet UITableView *myTableView;
@property (nonatomic,strong) NSArray *beasts;

- (IBAction)segmentChanged:(id)sender;

@end

@implementation RoleViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.myTableView.dataSource = self;
    self.myTableView.delegate = self;
    self.myTableView.rowHeight = 70;
    
}

- (NSArray *)beasts{
    if(_beasts == nil){
        //获取资源完整路径
        NSString *path = [[NSBundle mainBundle]pathForResource:@"magicBeasts" ofType:@"plist"];
        //读取资源文件
        NSArray *array = [NSArray arrayWithContentsOfFile:path];
        NSMutableArray *tempArray = [NSMutableArray array];
        for (NSDictionary* dict in array) {
            MagicBeastsModel *beast = [MagicBeastsModel beastsWithDict:dict];
            [tempArray addObject:beast];
            
        }
        _beasts = tempArray;
        [self sortBeasts:SORT_BY_ID];
        
    }
    return _beasts;
}

/**
 根据参数不同对tableview的内容进行不同的排序
 sortType的参数有:
     SORT_BY_ID 以ID升序排序
     SORT_BY_ATK 以攻击力升序排序
     SORT_BY_DEF 以防御力升序排序
     SORT_BY_TYPE 以攻击类型升序排序
 */

- (void)sortBeasts:(SortType)sortType{
    //拷贝一份beasts数组为可变数组 用于重新排序
    NSMutableArray *arr = [NSMutableArray arrayWithArray:self.beasts];
    //为了防止每次循环都判断一次sortType  使用代码块在循环体内部执行
    __block BOOL(^compare)(MagicBeastsModel *b1,MagicBeastsModel *b2) ;
    switch (sortType) {
        case SORT_BY_ID:
            compare = ^BOOL(MagicBeastsModel *b1,MagicBeastsModel *b2){
                if(b1.ID > b2.ID) return YES;
                return NO;
            };
            break;
        case SORT_BY_ATK:
            compare = ^BOOL(MagicBeastsModel *b1,MagicBeastsModel *b2){
                if(b1.atk > b2.atk) return YES;
                //如果atk相同 按ID排序
                else if(b1.atk == b2.atk){
                    if(b1.ID > b2.ID) return YES;
                }
                return NO;
            };
            break;
        case SORT_BY_DEF:
            compare = ^BOOL(MagicBeastsModel *b1,MagicBeastsModel *b2){
                if(b1.def > b2.def) return YES;
                //如果def相同 按ID排序
                else if(b1.def == b2.def){
                    if(b1.ID > b2.ID) return YES;
                }
                return NO;
            };
            break;
        case SORT_BY_TYPE:
            compare = ^BOOL(MagicBeastsModel *b1,MagicBeastsModel *b2){
                if([b1.type compare:b2.type] == NSOrderedAscending) return YES;
                //如果类型相同 按ID排序
                else if([b1.type compare:b2.type] == NSOrderedSame){
                    if(b1.ID > b2.ID) return YES;
                }
                return NO;
            };
            break;
        default:
            return NSLog(@"参数有误");
    }
    
    for (int i=0; i<arr.count; i++) {
        for(int j=i+1; j<arr.count; j++){
            if(compare(arr[i],arr[j])){ //执行代码块中的判定规则
                MagicBeastsModel *temp = arr[i];
                arr[i] = arr[j];
                arr[j] = temp;
            }
        }
    }
    self.beasts = [NSArray arrayWithArray:arr];
}

//segment切换后的响应事件
- (IBAction)segmentChanged:(id)sender {
    UISegmentedControl *seg = (UISegmentedControl *) sender;
    //NSLog(@"segment : %ld",seg.selectedSegmentIndex);
    switch (seg.selectedSegmentIndex) {
        case 0:
            [self sortBeasts:SORT_BY_ID];
            break;
        case 1:
            [self sortBeasts:SORT_BY_ATK];
            break;
        case 2:
            [self sortBeasts:SORT_BY_DEF];
            break;
        case 3:
            [self sortBeasts:SORT_BY_TYPE];
            break;
    }
    //排序完需要重新刷新tableView
    [self.myTableView reloadData];
}

//返回tableview的行数
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.beasts.count;
}

//返回每一行对应的cell
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    static NSString *ID = @"beast";
    MagicBeastsCell *cell = [tableView dequeueReusableCellWithIdentifier:ID];
    if(cell == nil){
        cell = [[[NSBundle mainBundle]loadNibNamed:@"MagicBeastsCell" owner:nil options:nil]lastObject];
    }
    cell.beast = self.beasts[indexPath.row];//调用了重写的set方法
    cell.selectedBackgroundView.backgroundColor = AppSettings.selectedCellColor;//设置选中cell的背景色
    return cell;
}

//当有cell被选中时
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    //定位到当前选择的cell 用于获取cell数据
    MagicBeastsCell *cell = (MagicBeastsCell *) [self tableView:self.myTableView cellForRowAtIndexPath:indexPath];
    //设置弹窗消息
    UIAlertController *alertVC = [UIAlertController alertControllerWithTitle:nil message:[NSString stringWithFormat:@"确认选择幻兽%ld吗？",cell.beast.ID]  preferredStyle:UIAlertControllerStyleAlert];
    //设置弹窗按钮
    [alertVC addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil]];
    [alertVC addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [AppSettings shareSettings].myBeast = self.beasts[indexPath.row];
        [self.presentingViewController dismissViewControllerAnimated:YES completion:nil];
        //NSLog(@"点击确认");
        MagicBeastsModel *beast = [AppSettings shareSettings].myBeast;
        
        //将选中的beast封装成dictionary
        NSDictionary *dict = [NSDictionary dictionaryWithObjectsAndKeys:[[NSNumber alloc] initWithInteger:beast.ID],@"ID",[[NSNumber alloc] initWithInteger:beast.atk],@"atk",[[NSNumber alloc] initWithInteger:beast.def],@"def",beast.type,@"type",beast.icon,@"icon",nil];
        //再加上level属性 写入文件
        NSLog(@"level2 : %ld",[AppSettings shareSettings].level);
        NSLog(@"level2 : %@",[[NSNumber alloc] initWithInteger:[AppSettings shareSettings].level]);
        NSDictionary *dict2 = [NSDictionary dictionaryWithObjectsAndKeys:[[NSNumber alloc] initWithInteger:[AppSettings shareSettings].level],@"level",dict,@"beast", nil];
        
        NSString *path = [[AppSettings dataFilePath]stringByAppendingString:@"/user.plist"];
        [dict2 writeToFile:path atomically:YES];
        NSLog(@"file writen ok ,%@",path);
    }]];
    //显示弹窗
    [self presentViewController:alertVC animated:YES completion:^{
        //执行完后取消选中标记
        [self.myTableView deselectRowAtIndexPath:indexPath animated:YES];
    }];

}
@end
